qui(function(require, exports, module) {
    PreSet.Edit = function(options) {
        this.dao = PreSet.Dao;
        this.options = $.extend(true, {}, options);
        this.modify = Com.url.getQueryValue("modify",location.href);
        this.channel_id = Com.url.getQueryValue("channel_id",location.href);
        this.channel_name = Com.url.getQueryValue("channel_name",location.href);

        this.album_id = Com.url.getQueryValue("album_id",location.href) ? Com.url.getQueryValue("album_id",location.href) : "";
        this.album_name = Com.url.getQueryValue("album_name",location.href) ? Com.url.getQueryValue("album_name",location.href) : "";
        this.scale = Com.url.getQueryValue("scale",location.href) ? Com.url.getQueryValue("scale",location.href) : "";
        this.repeat_info = Com.url.getQueryValue("repeat_info",location.href) ? Com.url.getQueryValue("repeat_info",location.href) : "";
        this.start_time = Com.url.getQueryValue("start_time",location.href) ? Com.url.getQueryValue("start_time",location.href) : "";
        this.stop_time = Com.url.getQueryValue("stop_time",location.href) ? Com.url.getQueryValue("stop_time",location.href) : "";
        this.priority = Com.url.getQueryValue("priority",location.href) ? Com.url.getQueryValue("priority",location.href) : "0";
        this.util = PreSet.Util || {};
        this.construct = options.construct || function() {
            this.init();
        };
        this.config = $.extend({}, options.config);
        // 放在最下方立即执行f
        this.construct.call(this);
    };

    PreSet.Edit.prototype = {
        initConfig: function() {
			return true;
		},
        init: function() {
        },

        run: function() {
            var self = this;
            var $container = self.options.$container;
            this.init();
            self.initConfig();

			self.bindEvent();
            self.initSuggest();
            self.perpareData();
        },

        perpareData: function() {
            var self = this;
            $('#operate').val(self.modify);
            $('#channel_id').val(self.channel_id);

            $('input[name="thriftVideo.albumId"]').val(self.album_name);
            $('#album_id').val(self.album_id);
            $('#album_name').val(self.album_name);
            $('input[name="start_time"]').val(self.start_time);
            $('input[name="stop_time"]').val(self.stop_time);

            var repeat_info_array = self.repeat_info.split(',');
            var repeat_info_html = "";
            for(var i=1; i<8; i++) {
                var checked = "";
                for(var j=0; j<repeat_info_array.length; j++) {
                    if (i == repeat_info_array[j]) {
                        checked ="checked='checked'";
                        break;
                    }
                }
                repeat_info_html += "<label class='checkbox inline'><input type='checkbox' name='repeat_info' value='" + i + "' " + checked + ">" + PreSet.Config.REPEAT_INFO[i-1] + "</label>";
            }
            $('#repeat_info_div').html(repeat_info_html);

            var scale_html = "";
            for (var i=0; i<3; i++) {
                var checked = PreSet.Config.SCALE_VALUE[i]==self.scale ? "checked='checked'" : '';
                scale_html += "<label class='radio inline'> <input type='radio' name='scale' value='" + PreSet.Config.SCALE_VALUE[i] + "' " + checked + " >" + PreSet.Config.SCALE[i] + "</label>";
            }
            $('#scale_div').html(scale_html);

            var priority_html = "";
            for (var i=3; i>=0; i--) {
                var checked = PreSet.Config.PRIORITY_VALUE[i]==self.priority ? "checked='checked'" : '';
                priority_html += "<label class='radio inline'> <input type='radio' name='priority' value='" + PreSet.Config.PRIORITY_VALUE[i] + "' " + checked + " >" + PreSet.Config.PRIORITY[i] + "</label>";
            }
            $('#priority_div').html(priority_html);
        },
        bindEvent: function() {
            var self = this;

			jQuery.validator.addMethod("isValidTime", function(value, element, param) {

				var isValidTime = function(timeStr) {
										var date = '00:00:00';
										if (!timeStr || (timeStr.length < date.length) || ('string' !== typeof timeStr)) {
											return false;
										}
										try {
											var parts = (timeStr || '').split(':');
											if (parts.length > 3) {
												return false;
											}

											// var minute = parseInt(parts[0], 10);
											// var second = parseInt(parts[1], 10);
											var hour   = Number(parts[0]).toFixed(0);
											var minute = Number(parts[1]).toFixed(0);
											var second = Number(parts[2]).toFixed(0);

											if ((parts[0].indexOf('.') != -1) || (parts[1].indexOf('.') != -1)|| (parts[2].indexOf('.') != -1)) {
												return false;
											}
											if (isNaN(hour) || isNaN(minute) || isNaN(second)) {
												return false;
											}
											if ((hour>=0 && hour<24) && (minute >= 0 && minute<60) && (second >= 0 && second < 60)) {
												return true;
											}
										} catch (e) {
											console.log(e.message);
										}
										return false;
									};

				return isValidTime(value);
			});


            var $container = self.options.$container;
            var $submit = $container.find('#Submit');
            var validator = self.getValidator();

			$form = $container;
			$form.find('input[name="start_time"]').timepicker({
				onClose: function(selectedDate) {
					$form.find('input[name="start_time"]').timepicker("option", selectedDate);
				},
				timeFormat: 'HH:mm:ss'
			});
			$form.find('input[name="stop_time"]').timepicker({
				onClose: function(selectedDate) {
					$form.find('input[name="stop_time"]').timepicker("option", selectedDate);
				},
				timeFormat: 'HH:mm:ss'
			});

            $submit.on('click', function() {
                var _save = function(data) {
                    $('#pageAlertValudError').hide();
                    $(document).tips({
                        content: "页面提交中",
                        type: "loading"
                    });
                    self.save(data);
                };
				var success = validator.form();
                var data = self.getParam();

				if (success){
					_save(data);
				}

            });
        },
        initSuggest:function(){
            var self = this;
            var $container = self.options.$container;
            var type = 'properTitle';
            var tpl = '<div><div class="contract-item">{{html varCatalogStatusColor }}' +
                                '<span class="contract-width100">${entityId}</span>' +
                                '<span class="contract-width150">{{html displayName }}</span>' +
                                '<span class="contract-width150">{{html properTitle }}</span>' +
                                '<span class="contract-width80" >${channelName}</span>' +
                                '<span class="contract-width80" >${categoryName}</span>' +
                                '<span class="contract-width50">${totalNumberOfEpisodes}</span>' +
                                '<span class="contract-width100">${globalPublishDate}</span>' +
                                '</div></div>';
            var title = {
                            entityId: '专辑ID',
                            qipuId: '奇谱ID',
                            displayName: '专辑显示名(无多发)',
                            properTitle: '专辑原名(无多发)',
                            channelName: '所属频道',
                            categoryName: '主频道',
                            totalNumberOfEpisodes: '总集数',
                            globalPublishDate: '发行时间'
                        };
            var getHtmlByData = function(data) {
                                var htmls = [];
                                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                                return htmlStr.html();
                            };
            var titleHtml = getHtmlByData(title);
            var albumIdSuggest = {
                options:{
                    source:"/api/redirect",
                    header: titleHtml,
                    method: "post",
                    multiple: false,
                    select: function(event, ui) {

                        if (ui && ui.item) {
                            $container.find('input[name="thriftVideo.albumId"]').attr('data-displayName', ui.item.properTitle);
                            $container.find('input[name="thriftVideo.albumId"]').attr('data-channel-id', ui.item.channel);
                            $container.find('input[name="ablum_id"]').val(ui.item.id);
                            $container.find('input[name="ablum_name"]').val(ui.item.properTitle.replace(/<b>|<\/b>/g,""));
                        }
                    },
                    parseValue: function() {
                        var val = this.element.val();
                        var ret = [];
                        if (val) {
                            var items = val.split(';');
                            $.each(items, function(i, item) {
                                item = item.split(',');
                                ret.push({
                                    value: item[1],
                                    id: item[0],
                                    label: item[1]
                                });
                            });
                        }
                        this._value('');
                        return ret;
                    },
                    getParam: function (term) {
                        var params = term.length == 0 ? {type:"properTitle", filter_EQI_isMainChannel:1}:{type:"properTitle", filter_EQI_isMainChannel:1, word: term};
                        var requestData = {url:  "http://lego.iqiyi.com/suggest/album", type: "get", params:params , needCookie: false};
                        return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                    },

                    process: function(json) {
                        var data = json.data;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, {
                                value: item[type]
                            }, item, {
                                // displayName: item[type],
                                id: item.entityId
                            }));
                        });
                        return ret;
                    },

                    template: function (item) {
                        return getHtmlByData(item);
                    }
                }
            };
            $("input[name='thriftVideo.albumId']").suggest(albumIdSuggest.options);
        },

        getValidator: function() {
            var $container = this.options.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, PreSet.Config.validator);

            return validator;
        },

        getParam: function() {
            var $container = this.options.$container;
            var self = this;
			var checkboxObj = null;
            var $elements = $.makeArray($container.prop('elements')).filter(function(item) {
				if($(item).attr("name") != "thriftVideo.albumId")
				{
					return true;
				}
				return false;
            });

			var checkboxVal = [];
            var name;
            var key;
			var params = {};

            $.each($elements, function() {
                name = this.name;
                if (name) {
                    if(name=='repeat_info') {
                        if(this.checked)
                        {
                            checkboxVal.push($(this).val());
                        }
                    } else if(name=="scale") {
                        if(this.checked)
                        {
                            params[name] = $(this).val();
                        }
                    } else if(name=="priority") {
                         if(this.checked)
                         {
                             params[name] = $(this).val();
                         }
                    } else {
                        params[name] = $(this).val();
                    }
                }
            });

			if(checkboxVal.length!==0){
                params['repeat_info']=JSON.stringify(checkboxVal);//params['repeat_info'].join(',');
            }
            return params;
        },
        save: function(data) {
            var request = {};
            request.url='http://lego.iqiyi.com/live2VOD/preSet/save';
            request.type='post';
            request.params = data;
            request.needCookie = {};
            var requestJson = JSON.stringify(request);

            this.dao.redirect({request:JSON.stringify(request)}, this.onSave);
        },
        onSave: function(json) {
            if (json.code == '200') {
                var url = '/epg/live2VOD_preset_home.html?channel_name='+Com.url.getQueryValue("channel_name",location.href)+'&channel_id='+Com.url.getQueryValue("channel_id",location.href);

                setTimeout(function() {
                    window.location.href = url;
                }, 2000);
                var html = '操作成功，系统将在两秒后跳转到节目页面,<a href="' + url + '" target="_self">立即跳转</a>';
                $(document).tips({
                    content: html,
                    type: "loading"
                });
            } else {
                $(document).tips({
                    content: json.msg,
                    type: "error"
                });
            }

        }

    };

});
